package ${projectPackage}.page;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Region;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
import ldh.fx.component.LWindowBase;
import ldh.fx.transition.FadeOutRightBigTransition;

import java.io.IOException;
import java.util.function.Consumer;

public class LoginPage extends LWindowBase {

    @FXML private Region topRectangle;
    @FXML private Region buttomRectangle;
    @FXML private GridPane loginPane;

    private Rectangle clip = new Rectangle();
    private Consumer<?> consumer = null;

    private Stage STAGE;

    public LoginPage(double width, double height) {
        super();
        buildMovable(this);
        this.setPrefHeight(height);this.setMinHeight(height);
        this.setPrefWidth(width);this.setMinWidth(width);

        loadFxl();
//        topRectangle.setWidth(width-3);
//        topRectangle.setHeight(height/2-1);
//        buttomRectangle.setWidth(width-3);
//        buttomRectangle.setHeight(height/2-2);

        AnchorPane.setBottomAnchor(topRectangle, height/2);
        AnchorPane.setTopAnchor(buttomRectangle, height/2);

        AnchorPane.setTopAnchor(loginPane, (height-loginPane.getPrefHeight())/2);
        AnchorPane.setLeftAnchor(loginPane, (width-loginPane.getPrefWidth())/2);

        clip.setWidth(width);
        clip.setHeight(height);
        this.setClip(clip);

    }

    public void setConsumer(Consumer<?> consumer) {
        this.consumer = consumer;
    }

    private void loadFxl() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/page/LoginPage.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    public void setStage(Stage stage) {
        this.STAGE = stage;
    }

    @FXML
    private void loginAction() throws Exception {
        close();
        if (consumer != null) {
            consumer.accept(null);
        }
    }

    @FXML
    public void closeBtn() {
        close();
    }

    private void close() {
        FadeOutRightBigTransition fadeOutRightTransition = new FadeOutRightBigTransition(this);
        fadeOutRightTransition.setOnFinished(e->{
            STAGE.close();
        });
        fadeOutRightTransition.playFromStart();
    }
}
